package com.example.myspring.servlet;

import com.example.myspring.entity.Student;
import com.example.myspring.util.ExcelServletUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.ArrayList;


@WebServlet(name = "ExcelServlet", value = "/ExcelServlet")
@MultipartConfig
public class ExcelServlet extends HttpServlet {

    private void initStudent(Student student, int cellNumber, String cellValue) {
        //非空判断
        if (cellValue.isEmpty()) return;
        //输出单元格值
        switch (cellNumber) {
            case 0:
                student.setName(cellValue);
                break;
            case 1:
                student.setSex(cellValue);
                break;
            case 2:
                student.setAge(cellValue);
                break;
            case 3:
                student.setAddress(cellValue);
                break;
            default:
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //创建对象集合
        ArrayList<Student> Students = new ArrayList<Student>();

        //拿到数据
        Part filePart = req.getPart("excelFile");
        //获取输入流
        InputStream fileContent = filePart.getInputStream();
        //工作簿
        Workbook wb = new XSSFWorkbook(fileContent);
        //工作表
        Sheet sheet = wb.getSheetAt(0);//表
        //首行
        Row rowTitle = sheet.getRow(0);//行
        //获取当前表总行数
        int rowCount = sheet.getPhysicalNumberOfRows();
        //遍历全部行
        for (int rowNumber = 0; rowNumber < rowCount; rowNumber++) {
            //拿到当前行数据
            Row rowData = sheet.getRow(rowNumber);
            //非空判断
            if (rowData == null) continue;
            //初始化对象
            Student student = new Student();
            //拿到当前行总单元格数量
            int cellCount = rowTitle.getPhysicalNumberOfCells();
            //根据当前行数据遍历当前行单元格
            for (int cellNumber = 0; cellNumber < cellCount; cellNumber++)
                initStudent(student, cellNumber, ExcelServletUtil.selectCellForRow(rowData, cellNumber));

            Students.add(student);//向集合中添加对象
        }
        System.out.println(Students);

        req.setAttribute("Students", Students);//写入请求头域
        req.getRequestDispatcher("excelShow.jsp").forward(req, resp);//转发至展示界面
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
